package sword_offer;

import common.ListNode;

/**
 * @ClassName _25MergeTwoList
 * @Description: 合并两个已排序链表
 * @Author: yongliang.ma
 * @Create_time:2022/10/9 13:43
 */
public class _25MergeTwoList {
    public static void main(String[] args) {
        ListNode _1node = new ListNode(1);
        ListNode _2node = new ListNode(2);
        ListNode _3node = new ListNode(3);
        _1node.next = _2node;
        _2node.next = _3node;

        ListNode _4node = new ListNode(1);
        ListNode _5node = new ListNode(2);
        ListNode _6node = new ListNode(4);
        _4node.next = _5node;
        _5node.next = _6node;

        ListNode listNode = new _25MergeTwoList().mergeTwoList(_1node, _4node);
        System.out.println(listNode);
    }

    // 分别从两个链表头部取数据
    public ListNode mergeTwoList(ListNode l1, ListNode l2){
        ListNode head = new ListNode(0);
        ListNode cursor = head, temp = null;
        while (l1 != null && l2 != null){
            if (l1.val < l2.val){
                // 接l1
                temp = l1;
                l1 = l1.next;

                cursor.next = temp;
                cursor = cursor.next;
            }else {
                // 接l2
                temp = l2;
                l2 = l2.next;

                cursor.next = temp;
                cursor = cursor.next;
            }
        }

        if (l1 != null){
            cursor.next = l1;
        }
        if (l2 != null){
            cursor.next = l2;
        }

        return head.next;
    }
}
